﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace UtilLib.Text
{
	class RazorFormat
	{
		/// <summary>
		/// 用类Razor Engine的方式格式化字符串
		/// </summary>
		/// <see cref="http://www.cnblogs.com/TianFang/archive/2013/09/15.html"/>
		/// <example>
		///		<code>
		///			string template = "Hello @Name! Welcome to C#!";
		///			string result = RazorFormat.Format(template, new { Name = "World" });
		///		</code>
		/// </example>
		public static string Format(string template, object data)
		{
			return Regex.Replace(template, @"@([\w\d]+)", match => GetValue(match, data));
		}

		static string GetValue(Match match, object data)
		{
			var paraName = match.Groups[1].Value;
			try
			{
				var proper = data.GetType().GetProperty(paraName);
				return proper.GetValue(data).ToString();
			}
			catch (Exception)
			{
				var errMsg = string.Format("找不到名为'{0}'的值", paraName);
				throw new ArgumentException(errMsg);
			}
		}
	}
}
